﻿angular.module('paperless').directive('busyClick', function ($parse, $q) {//notificationService
    'use strict';
        return {
        restrict: 'A',
        priority: 0,
        //terminal: true,
        link: function (scope, element, attrs) {
            var successMessage = attrs.success,
                errorMesssage = attrs.error || 'An error occured, please try again',
                modal = attrs['targetModal'],
                action = $parse(attrs['busyClick']);

            function releaseClick() {
                element.removeClass('disabled').removeAttr('disabled');

                if (modal) {
                    $('#' + modal).modal('hide');
                    //bug
                    $('body').removeClass('modal-open');
                    $('.modal-backdrop').remove();
                }
            }

            element.on('click', function () {
                element.addClass('disabled').attr('disabled', 'disabled');
                var promise = action(scope);

                if (promise && promise.finally) {
                    promise
                        .then(function (promise) {
                            var def;

                            if (promise && (promise.exceptionMessage || promise.message)) {
                                def = $q.defer();
                                def.reject(promise.exceptionMessage || promise.message);
                                return def.promise;
                            } else if (successMessage) {
                                //notificationService.success(successMessage);
                            }
                        })
                        .catch(function () {
                            if (errorMesssage) {
                                //notificationService.error(errorMesssage);
                            }
                        })
                        .finally(function () {
                            releaseClick();
                        });
                } else {
                    releaseClick();
                }
            });
        }
    };
});